package ifreecomm.nettyserver.netty;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;


@ChannelHandler.Sharable
public class EchoServerHandler extends ChannelInboundHandlerAdapter {

    private static final String TAG = "EchoServerHandler";
    private NettyServerListener mListener;

    public EchoServerHandler(NettyServerListener listener) {
        this.mListener = listener;
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
//    	System.out.println("channelReadComplete");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause) {
        cause.printStackTrace();                //5
        ctx.close();
        //6
    }
   /* @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {   //发送心跳
                ctx.channel().writeAndFlush("Heartbeat" + System.getProperty("line.separator"));
               // ctx.close();
            }
        }
    }*/

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg.equals("Heartbeat")){
            Log.d(TAG,"Heartbeat");
            return; //客户端发送来的心跳数据
        }
        AutoBrainProtocol body=(AutoBrainProtocol)msg;
        Log.e(String.valueOf(msg), "");
        Log.e(new String(body.getContent())+"","adasda");
        mListener.onMessageResponseServer(new String(body.getContent()),ctx.channel().id().asShortText());//将得到的字节数组转化为String
    }
    /**
     * 连接成功
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Log.e(TAG, "channelActive");
        mListener.onChannelConnect(ctx.channel());
//        NettyTcpServer.getInstance().setConnectStatus(true);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Log.e(TAG, "channelInactive");
//        NettyTcpServer.getInstance().setConnectStatus(false);
        mListener.onChannelDisConnect(ctx.channel());
    }
}
